package com.bjb.vr.server.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.dto.SyncTenant;
import com.bjb.vr.common.mapper.SyncTenantMapper;
import com.bjb.vr.common.utils.GuavaCacheUtil;
import com.bjb.vr.common.utils.LoadingCacheUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 初始化缓存配置
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/3/28 13:01
 */
@Slf4j
@Configuration
public class CacheConfig {

    @Value("${tenantDuration:1}")
    private long tenantDuration;

    @Resource
    private SyncTenantMapper syncTenantMapper;

    @Bean
    public void initTenantCache() {
        // 1、缓存字典数据--多条数据
        LoadingCache<String, List<String>> tenantCacheList = LoadingCacheUtil.asyncReloadMin(150L, tenantDuration, new CacheLoader() {

            @Override
            public Object load(Object o) {
                ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
                String tenantId = (String) o;
                LambdaQueryWrapper<SyncTenant> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(StringUtils.isNotBlank(tenantId), SyncTenant::getTenantId, tenantId);
                List<SyncTenant> syncTenants = syncTenantMapper.selectList(queryWrapper);
                return syncTenants.stream().map(SyncTenant::getTenantId).collect(Collectors.toList());
            }
        });
        GuavaCacheUtil.setTenantCache(tenantCacheList);
    }
}
